iT邦幫忙

2024 iThome 鐵人賽

DAY 2
0

Vue 的世界裡,插槽 (slot) 是一種非常強大的特性,
允許父組件將內容傳遞到子組件的指定位置。

Inside of every problem lies an opportunity.
每個問題裡都藏著一個機會。

slotProps 的優點

  1. 數據傳遞: 允許組件將內部數據傳遞給插槽內容。
  2. 自定義渲染: 根據這些數據自定義渲染邏輯。
  3. 靈活性: 提高了組件的可定制性和靈活性。

slotProps 的基本用法

<template>
  <DataTable :value="products">
    <Column field="name" header="Name">
      <template #body="slotProps">
        <span :style="{ color: slotProps.data.color }">
          {{ slotProps.data.name }}
        </span>
      </template>
    </Column>
  </DataTable>
</template>

使用了 DataTable 和 Column 元件來顯示一個產品表格。

  • slotProps.data:這是 Column 元件傳遞給插槽的資料。
  • {{ slotProps.data.name }}:顯示產品名稱。
  • :style="{ color: slotProps.data.color }":根據 data.color 動態設定字體顏色

PT (Pass Through) 和 slotProps 的結合使用
結合使用 PT (Pass Through) 和 slotProps,可以實現更精細的自定義。PT 可以讓我們控制組件內部的樣式,slotProps 則讓我們動態控制插槽內容。

<template>
  <DataTable :value="products">
    <Column field="name" header="Name" :pt="{ root: { class: 'custom-column' } }">
      <template #body="slotProps">
        <span :style="{ color: slotProps.data.color, fontWeight: 'bold' }">
          {{ slotProps.data.name }}
        </span>
      </template>
    </Column>
  </DataTable>
</template>

使用 PT 為 Column 元件添加了一個自定義的類,並結合 slotProps 動態控制內容的字體顏色和粗細。

結語

以上slotProps 和 PT工具,這兩者在 PrimeVue 的組件自定義和擴展中扮演了重要角色,更靈活地控制組件的外觀和行為。PT和slotProps的結合使用可以大大提高PrimeVue組件的可定制性和靈活性。

繼續學習並掌握這些工具,讓你在 PrimeVue 的開發過程中更加游刃有餘。
下一次,我們將更深入探討其他進階技術,幫助你在專案中實現更強大的功能。


上一篇
Day06 - 什麼是Pass Through (pt)?
下一篇
Day08- Forms(1)系列- Text-filed、switchButton
系列文
深入探索PrimeVue 套件及元件寫法29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言